<form lay-filter="purchaseSignTaskForm" class="layui-form open-form">
  <div class="open-model" id="warehouseStorageRecordFormByAdd">
    <div class="open-auto">
      <input name="id" type="hidden"/>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">入库类型</label>
          <input type="text" name="signCode" id="productInventoryType" id="productInventoryType" hidden/>
          <input type="text" name="inventoryQuantity" id="inventoryQuantity" id="inventoryQuantity" hidden/>
          <input type="text" name="netWeight" id="netWeight" id="netWeight" hidden/>
          <input type="text" name="grossWeight" id="grossWeight" id="grossWeight" hidden/>
          <input type="text" name="inventoryTypeId" id="inventoryTypeId" id="inventoryTypeId" hidden/>
          <div class="layui-input-block" style="margin-left: 130px">
            <select id="productInventoryId" name="productInventoryId" lay-filter="productInventoryId"
                    lay-search lay-verify="required"></select>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">质检记录编号</label>
          <input type="text" name="warehouseQualityTestingCode" id="warehouseQualityTestingCode" hidden/>
          <input type="text" name="qualityTestingId" id="qualityTestingId" hidden/>
          <div class="layui-input-block" style="margin-left: 130px">
            <div id="standardSku" style="display: flex; align-items: center">
              <select id="warehouseQualityTestingId" name="warehouseQualityTestingId"
                      lay-filter="warehouseQualityTestingId" lay-verify="required" lay-search></select>
            </div>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">所属报工单</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="processingReportCode" id="processingReportCode" class="layui-input"
                   disabled/>
          </div>
        </div>
      </div>

      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">上机记录编号</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="computerPracticeCode" id="computerPracticeCode" class="layui-input"
                   disabled/>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">制令单</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="schedulingPlanDetailCode" id="schedulingPlanDetailCode"
                   class="layui-input" disabled/>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">物料原始捆包号</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="userBundleCode" id="userBundleCode" class="layui-input" disabled/>
          </div>
        </div>
      </div>
      <!--      <div class="layui-col-xs3">-->
      <!--        <div class="layui-form-item">-->
      <!--          <label class="layui-form-label" style="width: 100px">产成品料号</label>-->
      <!--          <div class="layui-input-block" style="margin-left: 130px">-->
      <!--            <input type="text" name="customerProductCode" id="customerProductCode" class="layui-input" disabled />-->
      <!--          </div>-->
      <!--        </div>-->
      <!--      </div>-->
      <!--      <div class="layui-col-xs3">-->
      <!--        <div class="layui-form-item">-->
      <!--          <label class="layui-form-label" style="width: 100px">产成品规格码</label>-->
      <!--          <div class="layui-input-block" style="margin-left: 130px">-->
      <!--            <input type="text" name="productSpecCode" id="productSpecCode" class="layui-input" disabled lay-verify="required" />-->
      <!--          </div>-->
      <!--        </div>-->
      <!--      </div>-->
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">所属生产订单</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="productionOrderNumber" id="productionOrderNumber"
                   class="layui-input" disabled lay-verify="required"/>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">车间</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="productionLineName" id="productionLineName" class="layui-input"
                   disabled/>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">产线</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="workshopName" id="workshopName" class="layui-input" disabled/>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">上机时间</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="computerCreateTime" id="computerCreateTime" class="layui-input"
                   disabled/>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3" style="display: none;">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">产品id</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="warehouseProductId" id="warehouseProductId" class="layui-input"
                   disabled/>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3" style="display: none;">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">客户id</label>
          <div class="layui-input-block" style="margin-left: 130px">
            <input type="text" name="customerId" id="customerId" class="layui-input" disabled/>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label" style="width: 100px">入库仓库</label>
          <input type="text" name="warehouseFactoryAdministrationName" id="warehouseFactoryAdministrationName"
                 hidden/>
          <div class="layui-input-block" style="margin-left: 130px">
            <select
                    id="warehouseFactoryAdministrationId"
                    name="warehouseFactoryAdministrationId"
                    lay-filter="warehouseFactoryAdministrationId"
                    lay-search
                    lay-verify="required"></select>
          </div>
        </div>
      </div>
      <div class="layui-form-item">
        <div>
          <div class="layui-btn" id="addProduct" style="margin-top: 10px">新增库位</div>
          <div id="productList">
            <table class="layui-table" id="purchaseSignTaskProductTable"
                   lay-filter="purchaseSignTaskProductTable"></table>
          </div>
        </div>
      </div>

      <!--        <div class="open-details-title" style="margin-bottom: 5px;">库位信息</div>-->
      <!--        {{# if(d.eventName!="detail"){ }}-->
      <!--        <button class="layui-btn" id="addTableData" style="margin-top: 15px;">添加库位</button>-->
      <!--        {{# } }}-->
    </div>
    <div class="layui-form-item text-right">
      <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
      <button class="layui-btn" type="button" lay-filter="purchaseSignTaskFormSubmit" lay-submit>提交</button>
    </div>
  </div>
</form>
<script type="text/html" id="purchaseSignTaskProductTableFormBar">
  <!--  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="edit">入库</a>-->
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">移除</a>
</script>
<script>
  layui.use(["form", "table", "laydate", "layedit", "laydate"], async function () {
    $ = layui.jquery;
    var form = layui.form;
    var admin = layui.admin;
    var table = layui.table;
    var upload = layui.upload;
    var config = layui.config;
    var laytpl = layui.laytpl;
    var warehouseAreaList = [];
    var BundleList = [];
    let laydate = layui.laydate;


    await admin.initDataSelectPro(
            "warehouse/warehouse/admin/warehouseProductInventoryType/list",
            {
              limit: 999
            },
            "productInventoryId",
            "入库类型名称",
            async (d, obj) => {
              // $("#warehouseProductId").empty();
              form.val("purchaseSignTaskForm", {
                productInventoryType: ""
              });
              if (d.value) {
                form.val("purchaseSignTaskForm", {
                  productInventoryType: obj.name,
                  inventoryTypeId:d.value
                });

              }
            },
            "name"
    );

    await admin.initDataSelectPro(
            "warehouse/warehouse/qualityTesting/list?status=1",
            {
              limit: 999
            },
            "warehouseQualityTestingId",
            "质检记录编号",
            async (d, obj) => {
              form.val("purchaseSignTaskForm", {
                warehouseQualityTestingCode: "",
                processingReportCode: "",
                computerPracticeCode: "",
                schedulingPlanDetailCode: "",
                userBundleCode: "",
                customerProductCode: "",
                productSpecCode: "",
                productionOrderNumber: "",
                productionLineName: "",
                workshopName: "",
                computerCreateTime: "",
                warehouseProductId: "",
                customerId: "",
                // sysBundleCode: ''
              });
              // table.reload("purchaseSignTaskProductTable", { data: [] });
              if (d.value) {
                form.val("purchaseSignTaskForm", {
                  // inventorySum: obj.inventorySum,
                  warehouseQualityTestingCode: obj.code,
                  processingReportCode: obj.processingReportCode,
                  computerPracticeCode: obj.computerPracticeCode,
                  schedulingPlanDetailCode: obj.schedulingPlanDetailCode,
                  userBundleCode: obj.userBundleCode,
                  customerProductCode: obj.customerProductCode,
                  productSpecCode: obj.productSpecCode,
                  productionOrderNumber: obj.productionOrderNumber,
                  productionLineName: obj.productionLineName,
                  workshopName: obj.workshopName,
                  computerCreateTime: obj.computerCreateTime,
                  warehouseProductId: obj.productId,
                  customerId: obj.customerId,
                  qualityTestingId: d.value
                });

                let res = await admin.reqPro("warehouse/warehouse/product/selectProductDetail?status=1", {qualityTestingId: d.value})
                BundleList = res.data.filter((v) => v.productStatus == 7);
                if(BundleList.length){
                  form.val("purchaseSignTaskForm", {
                    customerId: BundleList[0].customerId,
                  })
                }
                let allTableCont = table.cache["purchaseSignTaskProductTable"];

                allTableCont.map(i => {
                  i.userBundleCode = ''
                })
                table.reload("purchaseSignTaskProductTable", {data: allTableCont});
              }
            },
            "code"
    );


    await admin.initDataSelectPro(
            "warehouse/warehouse/admin/administration/list",
            {
              limit: 999
            },
            "warehouseFactoryAdministrationId",
            "入库仓库",
            async (d, obj) => {
              form.val("purchaseSignTaskForm", {
                warehouseFactoryAdministrationName: ""
              });
              table.reload("purchaseSignTaskProductTable", {data: []});
              if (d.value) {
                form.val("purchaseSignTaskForm", {
                  warehouseFactoryAdministrationName: obj.name
                });
                // if ($("#warehouseProductId").val()) {
                //   setTable($("#warehouseProductId").val(), d.value);
                // }
                admin.req(
                        "warehouse/warehouse/admin/warehouseFactoryArea/list",
                        {
                          warehouseId: d.value
                        },
                        (res) => {
                          warehouseAreaList = res.data;
                          table.reload("purchaseSignTaskProductTable");
                        }
                );
              }
            },

            "name"
    );


    function setTable(productId) {
      admin.req(
              "warehouse/warehouse/admin/administration/selectAll",
              {
                limit: 999,
                productId: productId
              },
              (res) => {
                if (res.code == 200) {
                  table.reload("purchaseSignTaskProductTable", {data: res.data[0].warehouseFactoryShelfSpaceVOList});
                }
              }
      );
    }

    var insTb = table.render({
      elem: "#purchaseSignTaskProductTable",
      data: [],
      page: false,
      cellMinWidth: 100,
      height: 500,
      cols: [
        [
          {type: "numbers", title: "序号", height: 50},
          {
            field: "userBundleCode",
            align: "center",
            title: "捆包码（唯一码）",
            templet: function (d) {
              return admin.setTableSelect(
                      "userBundleCode",
                      BundleList.map((v) => {
                        return {
                          label: v.userBundleCode,
                          value: v.userBundleCode
                        };
                      }),
                      false,
                      "userBundleCode"
              )(d);
            }
          },
          // {
          //   field: "userBundleCode",
          //   title: "捆包码"
          // },
          // {
          //   field: "grossWeight",
          //   title: "毛重"
          // },
          // {
          //   field: "netWeight",
          //   title: "净重"
          // },
          {
            field: "warehouseAreaId",
            align: "center",
            title: "所在库区",
            templet: function (d) {
              return admin.setTableSelect(
                      "warehouseAreaId",
                      warehouseAreaList.map((v) => {
                        return {
                          label: v.name,
                          value: v.id
                        };
                      }),
                      false,
                      "warehouseAreaId"
              )(d);
            }
          },
          {
            field: "warehouseFactoryShelfSpaceId",
            align: "center",
            title: "所在库位",
            templet: function (d) {
              if (d.codeList) {
                return admin.setTableSelect(
                        "warehouseFactoryShelfSpaceId",
                        d.codeList.map((v) => {
                          return {
                            label: v.code,
                            value: v.id
                          };
                        }),
                        false,
                        "warehouseFactoryShelfSpaceId"
                )(d);
              } else {
                return "";
              }
            }
          },
          // { field: "inventorySum", align: "center", title: "当前库存" },

          {align: "center", toolbar: "#purchaseSignTaskProductTableFormBar", title: "操作", width: 100}
        ]
      ],
      done: (res, curr, count) => {
        form.val("purchaseSignTaskForm", {
          inventorySum: table.cache["purchaseSignTaskProductTable"].reduce((a, b) => a + b.inventorySum, 0)
        });
        admin.tableSelectChange("purchaseSignTaskProductTable", "userBundleCode", (index, value, tableData, field) => {
          console.log(value,"BundleList",BundleList)
          let obj = BundleList.find((v) => v.userBundleCode == value);
          if (tableData.filter((v) => v.userBundleCode == value).length > 1) {
            layer.msg("捆包码已存在");
            tableData[index].userBundleCode = "";
            table.reload("purchaseSignTaskProductTable", {
              data: tableData
            });
            return;
          }
          console.log( tableData[index]," tableData[index]")
          // tableData[index].userBundleCode = obj.userBundleCode;
          tableData[index].unit = obj.unit;
          tableData[index].grossWeight = obj.grossWeight;
          tableData[index].netWeight = obj.netWeight;
          tableData[index].proUnitId = obj.proUnitId;
          tableData[index].id = obj.id;
          table.reload("purchaseSignTaskProductTable", {
            data: tableData
          });

          form.val("purchaseSignTaskForm", {
            inventoryQuantity: tableData.filter((v) => v.userBundleCode).length,
            netWeight: tableData.reduce((a, b) => a + Number(b.netWeight || 0), 0),
            grossWeight: tableData.reduce((a, b) => a + Number(b.grossWeight || 0), 0)
          });
        });
      }
    });

    $("#warehouseStorageRecordFormByAdd .layui-table-body").css("overflow", "visible");
    $("#warehouseStorageRecordFormByAdd .layui-table-box").css("overflow", "visible");
    $("#warehouseStorageRecordFormByAdd .layui-table-view").css("overflow", "visible");
    admin.tableSelectChange("purchaseSignTaskProductTable", "warehouseAreaId", (index, value, tableData, field) => {
      admin.req(
              "warehouse/warehouse/admin/warehouseFactoryShelfSpace/list",
              {
                warehouseAreaId: value
              },
              (res) => {
                console.log(tableData, "11111111")
                tableData[index].warehouseFactoryShelfSpaceId = ''
                tableData[index].codeList = res.data;
                table.reload("purchaseSignTaskProductTable", {
                  data: tableData
                });

              }
      );
    });
    admin.tableSelectChange("purchaseSignTaskProductTable", "warehouseFactoryShelfSpaceId", (index, value, tableData, field) => {
      // console.log("tableData", tableData);
    });

    table.on("tool(purchaseSignTaskProductTable)", function (obj) {
      var data = obj.data;
      let warehouseFactoryShelfSpaceId = data.id;
      let warehouseAreaId = data.warehouseAreaId;

      if (obj.event === "edit") {
        if (!warehouseFactoryShelfSpaceId || !warehouseAreaId) {
          layer.msg("请先选择库区库位");
          return;
        }
        admin.formOpen({
          type: 1,
          area: "80%",
          offset: "5%",
          title: "入库作业",
          path: "components/warehouse/product/warehouseFinishedProductStorageRecordForm.html",
          success: function () {
            let obj = {
              waybillNum: $("#waybillNum").val(),
              warehouseProductId: $("#warehouseProductId").val(),
              customerProductCode: $("#customerProductCode").val(),
              inventorySum: $("#inventorySum").val(),
              warehouseOrderCode: $("#warehouseOrderCode").val(),
              warehouseOrderId: $("#warehouseOrderId").val(),
              qualityTestingId: $("#warehouseQualityTestingId").val(),
              warehouseQualityTestingCode: $("#warehouseQualityTestingCode").val(),
              warehouseFactoryAdministrationId: $("#warehouseFactoryAdministrationId").val(),
              warehouseFactoryAdministrationName: $("#warehouseFactoryAdministrationName").val(),
              SignInRecordName: $("#SignInRecordName").val(),
              customerName: $("#customerName").val(),
              customerId: $("#customerId").val(),
              productSpecCode: $("#productSpecCode").val(),
              productVarietyName: $("#productVarietyName").val(),
              productMarkName: $("#productMarkName").val(),
              productInventoryType: $("#productInventoryType").val(),
              inventoryTypeId: $("#productInventoryId").val(),
              warehouseFactoryShelfSpaceId: data.id,
              warehouseAreaId: data.warehouseAreaId,
              warehouseTypeName: data.warehouseTypeName

            };
            parentData.data = obj;
          }
        });
      } else if (obj.event === 'del') {
        // let data = table.cache["purchaseSignTaskProductTable"];
        // data.splice(obj.data.index, 1);
        // table.reload('purchaseSignTaskProductTable', {
        //   data: data, // 设置新的数据
        // });

        var rowIndex = $(obj.tr).data("index");

        // 从缓存中删除对应的数据
        let tableData = table.cache["purchaseSignTaskProductTable"];
        tableData.splice(rowIndex, 1); // 根据索引删除数据

        // 更新表格
        table.reload("purchaseSignTaskProductTable", {data: tableData});

        // layer.close(index);

        // 重新计算入库数量、净重、毛重
        form.val("purchaseSignTaskForm", {
          inventoryQuantity: tableData.filter((v) => v.userBundleCode).length,
          netWeight: tableData.reduce((a, b) => a + Number(b.netWeight || 0), 0),
          grossWeight: tableData.reduce((a, b) => a + Number(b.grossWeight || 0), 0)
        });

      }
    });
    $("#addProduct").click(function () {
      let warehouseQualityTestingId = $("#warehouseQualityTestingId").val();
      let warehouseProductId = $("#warehouseProductId").val();
      if (!warehouseQualityTestingId) {
        layer.msg("请先选择质检记录");
        return;
      }
      let data = table.cache["purchaseSignTaskProductTable"];
      data.unshift({
        code: "",
        warehouseAreaCode: "",
        inventorySum: "",
        userBundleCode: '',
        warehouseFactoryShelfSpaceId: '',
        warehouseAreaId: ''
      });
      table.reload("purchaseSignTaskProductTable", {
        data: data
      });
    });

    form.on("submit(purchaseSignTaskFormSubmit)", function (d) {
      const formData = {...d.field};
      let list = table.cache["purchaseSignTaskProductTable"];
      if (list.length === 0) {
        layer.msg("请添加库位", {icon: 2, time: 1000});
        return false;
      }
      if (list.some(item => item.userBundleCode == '')) {
        layer.msg("请选择捆包码（唯一码）", {icon: 2, time: 1000});
        return false;
      }
      if (list.some(item => item.warehouseAreaId == '')) {
        layer.msg("请选择库区", {icon: 2, time: 1000});
        return false;
      }
      if (list.some(item => item.warehouseFactoryShelfSpaceId == '')) {
        layer.msg("请选择库位", {icon: 2, time: 1000});
        return false;
      }
      list.forEach(i=>i.warehouseShelfSpaceId=i.warehouseFactoryShelfSpaceId)
      formData.warehouseProductInventoryVoList = list;
      admin.req(
              "warehouse/warehouse/finishedProductStorageRecord/addStorage",
              JSON.stringify(formData),
              function (res) {
                layer.closeAll("loading");
                if (res.code == 200) {
                  layer.msg("入库成功", {icon: 1});
                  table.reload("purchaseSignTaskTable");
                  layer.closeAll("page");
                } else {
                  layer.msg(res.msg, {icon: 2, time: 1000});
                }
              },
              "POST",
              true,
              "application/json; charset=utf-8"
      );
      return false;
    });
  });
</script>
<style>
  #warehouseStorageRecordFormByAdd .layui-table-cell {
    overflow: visible !important;
  }
</style>
